package com.yulian.repository.system_management;  

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import io.vertx.core.Future;
import io.vertx.core.Promise; 
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.SqlConnection;
import io.vertx.sqlclient.Tuple;

public class UserRepositoryImpl {
	final InternalLogger logger = Log4JLoggerFactory.getInstance(UserRepositoryImpl.class); 
	
	/**
	 * 根据用户的手机号查询用户信息 
	 * @param conn
	 * @param phone
	 * @return
	 */
	public Future<RowSet<Row>> getUserByPhone(SqlConnection conn, String phone){
		Promise<RowSet<Row>> promise = Promise.promise();
	    conn
	    .preparedQuery("select id, name, phone, salt, password, status from users where phone = $1")
	    .execute(Tuple.of(phone), ar2 -> {
	        //Release the connection to the pool
	    	conn.close();
	        if(ar2.succeeded()){
	          logger.info("getUserByPhone, query success: "+ ar2.result().rowCount());
	          promise.complete(ar2.result());
	        }else{
	        	logger.info("getUserByPhone, 失败: {}", ar2.cause().getMessage());	
	        	//用Promise来向上抛异常
	        	promise.fail(ar2.cause());
	        }
	    });
	    return promise.future();
	} 
	
	/**
	 * 获取用户的权限
	 * @param conn
	 * @param user_id
	 * @return
	 */
	public Future<RowSet<Row>> getUserPerms(SqlConnection conn, int user_id){
		Promise<RowSet<Row>> promise = Promise.promise();
 
		String sql = " SELECT distinct a.perm FROM  perms a left join roles_perms b on (a.perm_code=b.perm_code) left join users_roles c  on ( b.role_code = c.role_code ) "+ 
					" left join users d on ( c.user_code = d.user_code )  where d.id = $1 "; 
		conn
		.preparedQuery(sql)
		.execute(Tuple.of(user_id), ar2 -> {
	        //Release the connection to the pool
			conn.close();
	        if(ar2.succeeded()){
	          logger.info("getUserPerms, query success: "+ ar2.result().rowCount());
	          promise.complete(ar2.result());
	        }else{
	        	logger.info("getUserPerms, 失败: {}", ar2.cause().getMessage());	
	        	//用Promise来向上抛异常
	        	promise.fail(ar2.cause());
	        }
		});
	    return promise.future();
	}   
	
	/**
	 * 判断传入参数phone的用户是否存在
	 * @param conn
	 * @param phone
	 * @return
	 */
	public Future<RowSet<Row>> getUserPhone(SqlConnection conn, String phone){
		Promise<RowSet<Row>> promise = Promise.promise();
		String sql = "select phone from users where phone = $1 order by id desc limit 1";
	    conn
	    .preparedQuery(sql)
	    .execute(Tuple.of( phone) , ar -> {
	        //Release the connection to the pool
	        conn.close();
	        if(ar.succeeded()){
//	          logger.info("getUserPhone, query success: "+ ar.result().rowCount());
	          promise.complete(ar.result());
	        }else{
	        	logger.info("getUserPhone, 失败: {}", ar.cause().getMessage());	
	        	//用Promise来向上抛异常
	        	promise.fail(ar.cause());
	        }
	    });
	    return promise.future();
	} 
	
	public Future<RowSet<Row>> getPhoneById(SqlConnection conn, long id, String phone){
		Promise<RowSet<Row>> promise = Promise.promise();
		String sql = "select phone from users where phone = $1 and id != $2  order by id desc limit 1";
	    conn
	    .preparedQuery(sql)
	    .execute(Tuple.of( phone,id) , ar -> {
	        //Release the connection to the pool
	        conn.close();
	        if(ar.succeeded()){
//	          logger.info("getUserPhone, query success: "+ ar.result().rowCount());
	          promise.complete(ar.result());
	        }else{
	        	logger.info("getUserPhone, 失败: {}", ar.cause().getMessage());	
	        	//用Promise来向上抛异常
	        	promise.fail(ar.cause());
	        }
	    });
	    return promise.future();
	} 
	/**
	 * 获取 user_code
	 * @param conn
	 * @return
	 */
	public Future<RowSet<Row>> getUserCode(SqlConnection conn ){
		Promise<RowSet<Row>> promise = Promise.promise();
		String sql = "select user_code from users  order by id desc limit 1";
	    conn
	    .preparedQuery(sql)
	    .execute(  ar -> {
	        //Release the connection to the pool
	        conn.close();
	        if(ar.succeeded()){
//	          logger.info("getUserCode, query success: "+ ar.result().rowCount());
	          promise.complete(ar.result());
	        }else{
	        	logger.info("getUserCode, 失败: {}", ar.cause().getMessage());	
	        	//用Promise来向上抛异常
	        	promise.fail(ar.cause());
	        }
	    });
	    return promise.future();
	}
	
	/**
	 * 插入新的用户数据
	 * @param conn
	 * @param user_code
	 * @param phone
	 * @param salt
	 * @param pbkPassword
	 * @param create_user
	 * @return
	 */
	public Future<RowSet<Row>> insertUser(SqlConnection conn,  String user_code, String phone, String salt,String pbkPassword,  String create_user){
		Promise<RowSet<Row>> promise = Promise.promise(); 
		//String pbkPassword = PBKDF2_OK.getPBKDF2(password, salt);
		String sql = "INSERT INTO users(user_code, phone, salt, password,create_user)"
				+ " VALUES ($1, $2, $3,  $4, $5 )  RETURNING id" ;
	    conn
	    .preparedQuery(sql)
	    .execute(Tuple.of( user_code, phone,salt,pbkPassword, create_user), ar2 -> {
	        //Release the connection to the pool
	        conn.close();
	        if(ar2.succeeded()){
	          logger.info("insertUser, insert success: "+ ar2.result().rowCount());
	          promise.complete(ar2.result());
	        }else{
	        	logger.info("insertUser, insert Failed");	
	        	//用Promise来向上抛异常
	        	promise.fail(ar2.cause());
	        }
	    });
	    return promise.future(); 
	}
	 
}
